package com.gulimall.search.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.gulimall.common.core.domain.Result;
import com.gulimall.common.domain.es.SkuEsModel;
import com.gulimall.search.service.ProductUpService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

import static com.gulimall.search.config.RestHighLevelClientConfig.COMMON_OPTIONS;

@Service
public class ProductUpServiceImpl implements ProductUpService {
    @Resource
    private RestHighLevelClient client;

    /**
     * 上架商品
     */
    @Override
    public Result productUp(List<SkuEsModel> skuEsModels) throws IOException {
        //构建request请求对象
        BulkRequest request = new BulkRequest();
        //构建请求数据,批量添加数据
        for (SkuEsModel skuEsModel : skuEsModels) {
            request.add(new IndexRequest("gulimall_product")
                    .id(skuEsModel.getSkuId().toString())
                    .source(JSONObject.toJSONString(skuEsModel), XContentType.JSON));
        }
        //发送请求
        client.bulk(request,COMMON_OPTIONS);
        return Result.ok();
    }
}
